import { useEffect, useRef } from 'react';
import type { Socket } from 'socket.io-client';
import { io } from 'socket.io-client';
import { useNavigate } from 'react-router-dom';
import { setId, setWsStatus } from '../../redux/slices/wsSlice';
import { useAppDispatch, useAppSelector } from '../../redux/hooks';
import { setFalseAnswer, setUserId, setUserName, sethasAnswer } from '../../redux/slices/userSlice';
import type { GameType } from '../../types/socketType';
import { setGame } from '../../redux/slices/gameSlice';
import { setActiveTheme } from '../../redux/themes/slices';
import { resetTimer, startTimer } from '../../redux/timer/timerSlice';

export default function useNewUser(): {
  joinRoomHandler: (data: { name: string; roomName: string | undefined }) => void;
} {
  const socketRef = useRef<null | Socket>(null);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const user = useAppSelector((state) => state.user);

  useEffect(() => {
    socketRef.current = io('/');

    const socket = socketRef.current;

    socket.on('connect', () => {
      dispatch(setWsStatus(true));
    });

    socket.on('connect_error', () => {
      dispatch(setWsStatus(false));
    });

    socket.on('my_name', (data: string) => {
      console.log('myname---', data);
      dispatch(setId(data));
      dispatch(setUserId(data));
    });

    socket.on('room_users', (data: GameType) => {
      dispatch(setGame(data));
      dispatch(setActiveTheme(data.themeId));
    });

    socket.on('start', (data: GameType) => {
      dispatch(setGame(data));
      dispatch(startTimer());
      navigate('/game');
    });

    socketRef.current.on('newScore', (data: GameType) => {
      dispatch(setGame(data));
    });

    socket.on('nextquestion', (data: GameType) => {
      dispatch(setGame(data));
      dispatch(setFalseAnswer());
      dispatch(resetTimer());
    });

    socketRef.current.on('results', (data: GameType) => {
      dispatch(setGame(data));
      navigate('/result');
    });
  }, []);

  const joinRoomHandler = (data: { name: string; roomName: string | undefined }): void => {
    const { name, roomName } = data;
    if (name.length < 10 && name !== '') {
      dispatch(setUserName(name));
      if (!socketRef.current) return;

      socketRef.current.emit('join_room', { user: { ...user, name }, roomName });
    } else {
      alert('Введите корректное имя');
    }
  };

  return { joinRoomHandler };
}
